package com.mycompany.app.common.audit.modification.hibernate.interceptor;

import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import com.mycompany.app.common.audit.modification.annotation.BasicAudit;
import com.mycompany.app.common.security.acegi.SecurityUtils;

/**
 * Set audit fields for Object annotated by BasicAudit annotation.
 * consideration: 存储前的两次反射可能会影响性能. 第一次 get AuditEmbeddedObject 第二次 invoke
 * setCreateInfo or setUpdateInfo method.
 * 
 * @author Shawn.guo
 */
@SuppressWarnings("serial")
public class BasicAuditInterceptor extends EmptyInterceptor {

    protected final Log logger = LogFactory.getLog(getClass());

    public boolean onSave(Object entity, Serializable id, Object[] state,
            String[] propertyNames, Type[] types) {

        boolean modified = false;

        logger.info("In AuditInterceptor.onSave    " + entity.getClass());
        if (entity.getClass().isAnnotationPresent(BasicAudit.class)) {
            @SuppressWarnings("unused")
            String currentUser = SecurityUtils.getCurrentLoginName();
         // invoke entity.auditEmbededObject.setUpdateInfo
            modified = true;
        }
        return modified;
    }

    public boolean onFlushDirty(Object entity, Serializable id,
            Object[] currentState, Object[] previousState,
            String[] propertyNames, Type[] types) {

        boolean modified = false;

        logger.info("In AuditInterceptor.onFlushDirty    " + entity.getClass());
        if (entity.getClass().isAnnotationPresent(BasicAudit.class)) {
            @SuppressWarnings("unused")
            String currentUser = SecurityUtils.getCurrentLoginName();
            // invoke entity.auditEmbededObject.setUpdateInfo
            modified = true;

        }
        return modified;

    }
}
